package com.example.socket;

import com.example.constant.sta;
import com.example.mapper.MachineMapper;
import com.example.mapper.SampleMapper;
import com.example.pojo.PicContent;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/start")
public class SocketProcess {
    @Autowired
    private SampleMapper sampleMapper;
    @Autowired
    private MachineMapper machineMapper;
    @Autowired
    private SocketServer socketServer;

    private static final String sourceFolder = "C:\\卷包";

    @RequestMapping("/verify")
    public boolean startVerify(@RequestParam("machineIds") List<Integer> machineIds) {
        boolean allSuccess = true;

        for (int machineId : machineIds) {
            Socket clientSocket = socketServer.getClientSocket(machineId);
            if (clientSocket == null || clientSocket.isClosed()) {
                log.info("设备 {} 未连接", machineId);
                allSuccess = false;
                continue;
            }

            try {
                OutputStream outputStream = clientSocket.getOutputStream();
                PicContent picContent = new PicContent();
                picContent.setMsgType("verify");

                picContent.setDownloadUrl("http://192.168.0.106:8881/download/");
                //picContent.setDownloadUrl("http://192.168.0.110:8881/download/");
                //picContent.setDownloadUrl("http://192.168.1.102:8881/download/");
                //picContent.setDownloadUrl("http://192.168.2.171:8881/download/");
                //picContent.setDownloadUrl("http://192.168.0.111:8881/download/");

                picContent.setFileList(sampleMapper.getFilename());
                picContent.setMachineID(machineMapper.getMachineIDById(machineId));

                ObjectMapper objectMapper = new ObjectMapper();
                String json = objectMapper.writeValueAsString(picContent);
                byte[] jsonData = json.getBytes(StandardCharsets.UTF_8);

                // 生成10字节长度字符串
                String lengthStr = String.format("%010d", jsonData.length);
                byte[] lengthBytes = lengthStr.getBytes(StandardCharsets.US_ASCII);

                // ========== 关键修改：构建完整数据包 ==========
                byte[] fullData = new byte[lengthBytes.length + jsonData.length];
                System.arraycopy(lengthBytes, 0, fullData, 0, lengthBytes.length);
                System.arraycopy(jsonData, 0, fullData, lengthBytes.length, jsonData.length);

                // 一次性发送完整数据
                outputStream.write(fullData);
                outputStream.flush();

                // 日志记录（可选）
                log.info("已发送完整数据到设备 {} (总长度: {}): {}",
                        machineId, fullData.length, new String(fullData, StandardCharsets.UTF_8));

            } catch (IOException e) {
                log.error("发送消息到设备 {} 失败", machineId, e);
                allSuccess = false;
            }
        }

        return allSuccess;
    }
}